﻿using System;
using Core.Log;
using Game;
using UnityEngine;

namespace Core.File {
    public interface ISerializable<T> {
        public string Serialize();
        public void Deserialize(string data);
    }
    public class FileOperator {
        private const string cPath = @"/Data/File/";
        
        public static void SaveData<T>(T obj,string fileName) where T : ISerializable<T> {
            string filePath = string.Concat(Application.dataPath,cPath,fileName, ".txt");
            string data = obj.Serialize();
            try {
                System.IO.File.WriteAllText(filePath, data);
                ADbg.LogF("[File] Saving string to file,FileName: {0}",filePath);
            } catch (Exception ex) {
                ADbg.LogEF("[File] Error Saving string to file,FileName: {0}",filePath);
            }
            
        }

        public static T ReadFile<T>(string fileName) where T : class,ISerializable<T>,new() {
            string filePath = string.Concat(Application.dataPath,cPath,fileName, ".txt");
            try {
                string data = System.IO.File.ReadAllText(filePath);
                ADbg.LogF("[File] Read data From file,FileName: {0}", filePath);
                try {
                    T obj = new T();
                    obj.Deserialize(data);
                    return obj;
                } catch (Exception ex) {
                    ADbg.LogEF("[File] Error Deserialize data From file.FileName: {0}",filePath);    
                }
            } catch (Exception ex) {
                T newObj = new T();
                SaveData(new T(),fileName);
                return newObj;
            }
            return null;
        }

    }
}